class Product < ActiveRecord::Base
  has_many :uploads, as: :imageable
  has_many :orders, dependent: :destroy, as: :product
  scope :ordered_products, -> { order("top DESC nulls last, top_at DESC nulls last") }
  scope :published, ->(time=Time.now){where("publish_time < ? or publish_time is null", time)}

  has_many :products_articles,:dependent => :destroy
  has_many :articles, :through => :products_articles

  mount_uploader :pdf, FileUploader

  before_save :set_top_at

  CATEGORIES = %w{ 去干吗 去哪里 }

  include ImgCrop
  # attached start
  has_attached_file :cover, :styles => { :small => "330x175#", :large => "800x800>" }, :processors => [:cropper]
  validates_attachment_content_type :cover, :content_type => /\Aimage/
  validates_attachment :cover, :size => { :in => 0..500.kilobytes }

  has_attached_file :top_cover, :styles => { :small => "960x320#", :large => "1200x400>" }, :processors => [:cropper]
  validates_attachment_content_type :top_cover, :content_type => /\Aimage/
  validates_attachment :top_cover, :size => { :in => 0..1500.kilobytes }

  def top_cover_geometry(style = :original)
    @geometry ||= {}
    @geometry[style] ||= Paperclip::Geometry.from_file(top_cover.path(style))
  end

  private

    def set_top_at
      self.top_at = Time.now if self.top && self.top_changed?
    end

end